﻿Ext.ns("Kwan");
var deskWidth, deskHeight;
Kwan = {
    SELECT: '请选择..',
    BEFORE_DEL_ALL: '确认要删除数据吗？<br>可能会删除与之相关的数据!<br>按【否】可以还能避免，确认一定要删除请按【是】',
    PROMPTED: '系统提示',
    ERR_NOSELECT: '请至少选择一项！',

    DEBUG: false,
    DEFAULT_PAGE_SIZE: 10,
    DATETIME_FORMAT: 'Y-m-d H:i:s',
    DATE_FORMAT: 'Y-m-d',
    CURRENT_YEAR: new Date().getFullYear(),
    CURRENT_MONTH: new Date().getMonth() + 1,
    META_REPOSITORY: {},

    now: function () {
        var date = Ext.Date.format(new Date(), 'Y-m-d H:i:s');
        return date;
    },

    log: function (val) {
        if (this.DEBUG != true)
            return false;
        if ('string' == typeof val) {
            Ext.log(val);
        } else {
            Ext.log(Ext.encode(val));
        }
    },

    // helper
    objToString: function (o) {
        var s = '{\n';
        for (var p in o)
            s += '    "<b>' + p + '</b>": "' + o[p] + '"\n';
        return s + '}';
    },
    htmlEditorRender: function (htmlEditor) {
        htmlEditor.tb.addSeparator();
        htmlEditor.tb.addButton({ handler: Kwan.insertHandler, iconCls: "icon-image", text: "图片", tooltip: '<b>插入图片</b><br>在本地计算机上传一张图片以展示。' });
    },
    insertHandler: function () {
        //txtContent_htmlEditor_Container.insertAtCursor("<img src=\"myimage.gif\">");
        winUploadNews.show();
    },
    uploadNews: function (id) {
        var textArea = Ext.getCmp(id);
        this.def.UploadNews(id, {
            success: function (result) {
                //var json = eval("(" + result + ")");
                textArea.insertAtCursor("<img src=\"" + result + "\">");
                winUploadNews.hide();
            }
        });
    },
    showNotify: function (title, msg) {
        return Ext.net.Notification.show({
            hideFx: { fxName: 'switchOff', args: [{}] },
            showFx: { args: ['C3DAF9', 1, { duration: 1.0}], fxName: 'frame' },
            hideDelay: 300, pinEvent: 'click',
            alignToCfg: { offset: [0, 10], position: 't-t' },
            html: title,
            title: msg
        });
    },

    showDeleteConfirm: function (obj, record) {
        return Ext.Msg.confirm(this.PROMPTED, this.BEFORE_DEL_ALL, function (btn) {
            if (btn == "yes") { obj.DeleteSelected(record); }
        });
    },
    getDeleteID: function (d) {
        var f = '';
        for (var i = 0; i < d.length; ++i) { f += d[i].EntityID + ','; }
        return f;
    },
    Tips: { Hot: '热门', Recommend: '推荐', Deleted: '隐藏', Enable: '启用', MemberOnly: '限制', IsComputer: '开启', IsMaQue: '开启' },
    IntIcons: { 0: 'icon-bulletcross', 1: 'icon-bullettick', 2: 'icon-ruby' },
    IntTips: { 0: '已禁用', 1: '免费', 2: 'VIP' },
    MatchTips: { Hot: '热门', Recommend: '推荐', Deleted: '隐藏', Enable: '启用', MemberOnly: '限制', IsComputer: ['是', '否'], IsMaQue: ['是', '否'] },
    BitTips: ['是', '否'],
    Icons: ['icon-bullettick', 'icon-bulletcross'],
    Debug: function (o) {
        document.write(this.objToString(o));
    },
    GetIDs: function (d) {
        var ids = '';
        for (i = 0; i < d.length; ++i) {
            ids += d[i].EntityID;
            if (i < (d.length - 1)) { ids += ',' }
        }
        return ids;
    },
    CheckDelete: function (d) {
        if (d.length < 1) { this.showNotify(this.PROMPTEDERR_NOSELECT, this.ERR_NOSELECT); return; }
        else {
            this.showDeleteConfirm(this.def, this.GetIDs(d));
        }
    },
    CellCommand: function (grid, record, command, rowIndex) {
        switch (command) {
            case "Edit": this.def.EditInfo(record.data.EntityID); break;
            case "Delete": this.showDeleteConfirm(this.def, record.data.EntityID); break;
            //case "EditRoleModule": this.def.GetRoleModule(record.data.EntityID); break;                                                                                                                                                           
            case "RoomStatus":
                var val = record.data['Status'];
                if (val == 2) { this.showNotify("已入住的房间不能被修改！", this.PROMPTED); return; }
                else {
                    var newVal = val == 0 ? 1 : 0;
                    this.def.ChangeState('[' + Ext.encode(record.data) + ']', 'Status' + '_' + newVal);
                }
                break;
            case "Status":
                var newVal = record.data[command] + 1;
                if (newVal > 3) { newVal = 1; }
                this.def.ChangeState('[' + Ext.encode(record.data) + ']', command + '_' + newVal); break;
            case "Scale":
                var newVal = record.data[command] + 1;
                if (newVal > 2) { newVal = 0; }
                this.def.ChangeState('[' + Ext.encode(record.data) + ']', command + '_' + newVal); break;
            default:
                var newVal = !record.data[command];
                this.def.ChangeState('[' + Ext.encode(record.data) + ']', command + '_' + newVal); break;
        }
    },
    prepareBit: function (grid, toolbar, rowIndex, record) {
        var item = toolbar.items.items[0],
            key = item.command,
            val = record.get(key),
            icon = val ? "icon-bullettick" : "icon-bulletcross",
            tips = val ? "已" + Kwan.Tips[key] : "未" + Kwan.Tips[key];
        item.setIconClass(icon);
        item.setTooltip(tips);
    },
    prepareInt: function (grid, toolbar, rowIndex, record) {
        var item = toolbar.items.items[0],
            key = item.command,
            val = record.get(key),
            icon = Kwan.IntIcons[val],
            tips = Kwan.IntTips[val];
        item.setIconClass(icon);
        item.setTooltip(tips);
    },
    tipRoomStatus: [['空净房', '空脏房', '维修房', '住客房', '保留房'], ['green', 'purple', 'orange', 'red', 'orange']],
    objStatus: { 'Room': this.roomStatus },
    prepareRoomStatus: function (d) {
        var template = '<span style="color:{0};">{1}</span>';
        var isTrue = d == 0;
        return String.format(template, isTrue ? "green" : "red", Kwan.roomStatus[d]);
    },
    ChangeToColorFont: function (d) {
        var template = '<span style="color:{0};">{1}</span>';
        var isTrue = d == '1';
        d = isTrue ? '是' : '否';
        return String.format(template, isTrue ? "green" : "red", d);
    },
    tipHas: [['无', '有'], ['red', 'green']],
    tipUser: [['禁用', '启用'], ['red', 'green']],
    tipCustomerType: ['普通宾客', 'VIP宾客', '协议宾客'],
    tipSex: ['女', '男'],
    tipIDType: ['', '居民身份证', '临时身份证', '军官证', '护照', '港澳同胞回乡证', '外国人出入境证', '外国人居留证'],
    tipCsStatus: [['系统作废', '未结账', '已结账', '已冲红', '已挂账', '已换房', '已免受'], ['red', 'blue', 'green', 'red', 'blue', 'blue', 'blue']],
    isCheckIN: function (d) {
        var template = '<span style="color:{0};">{1}</span>', color, tips;
        if (d === 0) { color = 'blue', tips = '未入住'; } else { color = 'red', tips = '入住中'; }
        return Ext.String.format(template, color, tips);
    },
    colorSex: function (d) {
        return Kwan.tipSex[d];
    },
    colorIDType: function (d) {
        return Kwan.tipIDType[d];
    },
    colorHas: function (d) {
        d = d ? 1 : 0;
        return Ext.String.format('<span style="color:{0};">{1}</span>', Kwan.tipHas[1][d], Kwan.tipHas[0][d]);
    },
    colorRoomStatus: function (d) {
        return Ext.String.format('<span style="color:{0};"><b>{1}</b></span>', Kwan.tipRoomStatus[1][d], Kwan.tipRoomStatus[0][d]);
    },
    colorUser: function (d) {
        return Ext.String.format('<span style="color:{0};"><b>{1}</b></span>', Kwan.tipUser[1][d], Kwan.tipUser[0][d]);
    },
    colorEnable: function (d) {
        d = d ? 1 : 0;
        return Ext.String.format('<span style="color:{0};"><b>{1}</b></span>', Kwan.tipUser[1][d], Kwan.tipUser[0][d]);
    },
    colorCsStatus: function (d) {
        return Ext.String.format('<span style="color:{0};"><b>{1}</b></span>', Kwan.tipCsStatus[1][d], Kwan.tipCsStatus[0][d]);
    },
    prepareBitImg: function (d) {
        var template = '<img src="/icons/{0}-png/ext.axd/" title="{1}" />';
        var img = d ? 'bullet_tick' : 'bullet_cross';
        var t = d ? '有效' : '无效';
        return String.format(template, img, t);
    },
    getRandom: function () { return Math.random(); },
    getImage: function (d) {
        return String.format('<img src="/upload/product/p160/{0}?' + Math.random() + '" width="100%" />', d);
    },
    updateTree: function (treePanel, command) {
        var id = treePanel.getSelectionModel().getSelectedNode().id;
        switch (command) {
            case "Rename": this.def.SetClassInfo(id); break;
            case "Remove": treePanel.removeNode(treePanel.menuNode); break;
            default: this.def.InitClassInfo(id); break;
        }
    },
    addTreeNode: function (treePanel) {
        this.def.InitClassInfo(id);
    },
    showMenu: function (node, e) {
        var menu = TreeContextMenu;
        if (node.browserEvent) {
            this.menuNode = this.getRootNode();
            menu.nodeName = "";
            this.getSelectionModel().clearSelections();
            e = node;
        }
        else {
            this.menuNode = node;
            menu.nodeName = node.text;
            node.select();
        }

        menu.showAt([e.getXY()[0], e.getXY()[1] + 18]);
        e.stopEvent();
    },
    jsonServicce: function (arg) {
        Ext.net.DirectMethod.request({
            cleanRequest: true,
            url: "/facade.axd",
            //json: true,
            params: { action: arg[0], tb: this.tb, data: arg[1], NV: arg[2] },
            success: function (result) {
                Ext.Msg.alert("Json Message", Ext.DomQuery.selectValue("string", result, ""));
            }
        });
    },
    createColumn: function (metas, noNum) {
        var c = [];
        if (!noNum) c.push({ xtype: 'rownumberer', maxWidth: 60 });
        for (i = 0; i < metas.length; i++) {
            if (!metas[i].ex_list) continue;
            var cfg = Ext.apply(metas[i].ex_list, {
                dataIndex: metas[i].name,
                header: metas[i].label
            });
            Ext.apply(cfg, metas[i].ex_list);
            c.push(cfg);
        }
        return c;
    },
    createModel: function (metas) {
        var c = ['EntityID'];
        for (i = 0; i < metas.length; i++) {
            c.push(metas[i].name);
        }
        return c;
    },
    createStore: function (metas, cfg, sorters) {
        var ds = Ext.create('Ext.data.Store', {
            autoLoad: true,
            pageSize: cfg.limit,
            remoteSort: true,
            remoteFilter: true,
            fields: this.createModel(metas),
            sorters: sorters || [{ property: 'EntityID', direction: 'DESC'}],
            proxy: { type: 'ajax', url: cfg.facade + '&s_method=list', reader: { type: 'json', root: 'data.data', totalProperty: 'data.total' }
            }
        });
        return ds;
    },
    f_status: ['空净房', '空脏房', '维修房', '住客房', '保留房'],
    bindForm: function (values, fp) {
        //Kwan.Debug(values);
        Ext.each(fp._fields.items, function (field) {
            if (field) {
                field.setValue(values[0][field.name]);
            }
        });
    },
    createFormItems: function (metas, fp) {
        items = [];
        metas = metas.sortObjectWith('sort', 'asc', function (id) { return parseInt(id); });
        fp = 'fp_' + fp + '_';
        for (var i = 0; i < metas.length; i++) {
            var ex_edit = metas[i].ex_edit;
            if (!ex_edit) continue;
            var item = { id: fp + metas[i].name, name: metas[i].name, fieldLabel: metas[i].label };
            if (ex_edit.xtype) {
                switch (ex_edit.xtype) {
                    case 'treecombo':
                        var store = Ext.getCmp(ex_edit.ex_combo.ds).store;
                        item = Ext.create("Kwan.ex.TreeCombo", { id: fp + ex_edit.ex_combo.field, name: ex_edit.ex_combo.field, store: store }); break;
                    case 'SimpleCombo':
                        item = Ext.create("Kwan.ex.SimpleCombo", { id: fp + metas[i].name, name: metas[i].name, ds: ex_edit.ex_combo.ds }); break;
                    case 'numberfield':
                    case 'datefield':
                        Ext.apply(item, ex_edit); break;
                    case 'checkboxfield':
                        Ext.apply(item, { xtype: 'kwanCheckbox' }); break;
                }
                if (ex_edit.cfg) {
                    Ext.apply(item, ex_edit.cfg);
                    if (ex_edit.cfg.allowBlank === false) Ext.apply(item, { labelStyle: 'color:red;font-weight:700;' });
                }
                Ext.apply(item, { fieldLabel: metas[i].label });
            }
            else {
                if (ex_edit.allowBlank === false) {
                    Ext.apply(item, { labelStyle: 'color:red;font-weight:700;' });
                }
                Ext.apply(item, { xtype: 'textfield' });
                Ext.apply(item, ex_edit);
                //item = this.createFieldConfig(allcfg);
            }
            //Ext.apply(item, { fieldLabel: metas[i].label });
            items.push(item);
        }
        return items;
    },
    copyRecordDataToForm: function (rec, form) {
        Ext.each(form._fields.items, function (field) {
            if (field.store) {                      //存在store的combo
                field.setValue(rec[field.name]);
                field.setRawValue(rec['ClassName']); // setRawValue
            } else {
                field.setValue(rec[field.name]);
            }
        });
    },
    layoutField: function (metas, groups, fp) {
        var cfg = {
            defaults: { flex: 1, style: { padding: '10px'} }
        }, items = [];
        Ext.each(groups, function (fields) {
            var items = [];
            var container = Ext.create('Ext.container.Container', cfg);
            Ext.each(fields, function (field) {
                Ext.each(metas, function (meta) {
                    if (meta.name == field) {

                    }
                });
                if (typeof (field) === 'string') {
                    var item = { id: fp + metas[i].name, name: metas[i].name };
                }
            });
            //container.items

        });
    },
    makeGroupItems: function (metas, column, fp) {
        metas = metas.sortObjectWith('sort', 'asc', function (id) { return parseInt(id); });
        fp = 'fp_' + fp + '_';
        for (var i = 0; i < metas.length; i++) {
            var ex_edit = metas[i].ex_edit;
            if (!ex_edit) continue;
            var item = { id: fp + metas[i].name, name: metas[i].name };
            if (ex_edit.xtype) {
                switch (ex_edit.xtype) {
                    case 'treecombo':
                        var store = Ext.getCmp(ex_edit.ex_combo.ds).store;
                        item = Ext.create("Kwan.ex.TreeCombo", { id: fp + ex_edit.ex_combo.field, name: ex_edit.ex_combo.field, store: store }); break;
                    case 'SimpleCombo':
                        item = Ext.create("Kwan.ex.SimpleCombo", { id: fp + metas[i].name, name: metas[i].name, ds: ex_edit.ex_combo.ds }); break;
                    case 'datefield':
                        Ext.apply(item, ex_edit); break;
                }
                Ext.apply(item, ex_edit.cfg);
            }
            else {
                Ext.apply(item, { xtype: 'textfield' });
                Ext.apply(item, ex_edit);
                //item = this.createFieldConfig(allcfg);
            }
            Ext.apply(item, { fieldLabel: metas[i].label });
            items[metas.group - 1] = item;
        }
        return items;
    }
};